package org.chispa.api.domain;

import java.io.IOException;
import java.io.StringWriter;

import org.chispa.api.util.JSONManager;
import org.chispa.api.util.PropertyLoader;
import org.chispa.repository.bin.IDomainData;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;

/**
 * @author  bgabor
 */
class RestfulNumberRetriever implements NumberRetriever {
	
	/**
	 * @uml.property  name="proxy"
	 * @uml.associationEnd  
	 */
	private IDomainData proxy;
		
	RestfulNumberRetriever()
	{
		String uri=PropertyLoader.getProperty(getClass(), "uri");
		ClientResource cr = new ClientResource(uri);
		proxy=cr.wrap(IDomainData.class);
	}

	@Override
	public DomainParameter queryParams(String uuid, String ns, String param) {
		try {
			JsonRepresentation rep = new JsonRepresentation(JSONManager.paramsToJSON(uuid, ns, param));
			Representation reply=proxy.queryParam(rep);
			StringWriter writer=new StringWriter();
			try {
				reply.write(writer);
				JSONObject json=new JSONObject(writer.toString());
				return JSONManager.JSONtoDomain(json);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void addData(DomainParameter data) {
		JsonRepresentation rep;
		try {
			rep = new JsonRepresentation(JSONManager.domainToJSON(data));
			proxy.addParam(rep);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
	}

}
